import React, { useState } from 'react'
import { View } from 'remax/one'
import { cloud, showToast } from 'remax/wechat'
import { Button, Popup } from 'annar'
import { requestCloud } from '@/hooks/use-cloud'
import useUser from '@/hooks/use-user'
import styles from './index.css'

export default ({
  children,
  open = true,
  onClose,
  onLogin,
}: {
  children?: React.ReactNode
  open?: boolean
  onClose?: () => void
  onLogin?: () => void
}) => {
  const { data, mutate } = useUser()
  const [user, setUser] = useState<WBG.UserInfo>()

  if (children) {
    if (data === undefined) {
      return null
    } else if (data) {
      return <>{children}</>
    }
  }

  const getUserInfo = ({
    detail: { userInfo },
  }: {
    detail: { userInfo: WBG.UserInfo }
  }) => {
    if (userInfo) {
      const { nickName, avatarUrl, gender } = userInfo
      setUser({ nickName, avatarUrl, gender })
    }
  }
  const getPhoneNumber = async ({
    detail: { cloudID },
  }: {
    detail: { cloudID: string }
  }) => {
    if (cloudID) {
      try {
        await requestCloud('login', { user, phone: cloud.CloudID(cloudID) })
        const data = await mutate()
        if (data) {
          onClose && onClose()
          onLogin && onLogin()
        }
      } catch ({ errMsg }) {
        showToast({ title: '网络错误', icon: 'none' })
      }
    }
  }

  return (
    <Popup
      open={open}
      closeable={!!onClose}
      style={{ textAlign: 'center', width: '80%', padding: 30 }}
      onClose={onClose}
    >
      <View className={styles.title}>需要登录</View>
      {user ? (
        <Button
          look="secure"
          size="large"
          block={true}
          openType="getPhoneNumber"
          onGetPhoneNumber={getPhoneNumber}
        >
          授权获取手机号
        </Button>
      ) : (
        <Button
          look="secure"
          size="large"
          block={true}
          openType="getUserInfo"
          onGetUserInfo={getUserInfo}
        >
          授权获取个人信息
        </Button>
      )}
    </Popup>
  )
}
